import { apiClient } from './client'
import { LoginRequest, RegisterRequest, User, AuthTokens, ApiResponse } from '@/types/api'

export class AuthService {
  // Login
  async login(credentials: LoginRequest): Promise<ApiResponse<{ user: User; tokens: AuthTokens }>> {
    const response = await apiClient.post('/auth/login', credentials)
    
    if (response.success && response.data) {
      // Store tokens
      apiClient.setTokens(response.data.tokens.accessToken, response.data.tokens.refreshToken)
    }
    
    return response
  }

  // Register
  async register(userData: RegisterRequest): Promise<ApiResponse<{ user: User; tokens: AuthTokens }>> {
    const response = await apiClient.post('/auth/register', userData)
    
    if (response.success && response.data) {
      // Store tokens
      apiClient.setTokens(response.data.tokens.accessToken, response.data.tokens.refreshToken)
    }
    
    return response
  }

  // Logout
  async logout(): Promise<ApiResponse> {
    try {
      const response = await apiClient.post('/auth/logout')
      return response
    } finally {
      // Always clear tokens, even if logout request fails
      apiClient.clearTokens()
    }
  }

  // Get current user
  async getCurrentUser(): Promise<ApiResponse<{ user: User }>> {
    return apiClient.get('/auth/me')
  }

  // Refresh token
  async refreshToken(): Promise<ApiResponse<{ tokens: AuthTokens }>> {
    const refreshToken = localStorage.getItem('refreshToken')
    if (!refreshToken) {
      throw new Error('No refresh token available')
    }

    const response = await apiClient.post('/auth/refresh', { refreshToken })
    
    if (response.success && response.data) {
      // Update stored tokens
      apiClient.setTokens(response.data.tokens.accessToken, response.data.tokens.refreshToken)
    }
    
    return response
  }

  // Forgot password
  async forgotPassword(email: string): Promise<ApiResponse> {
    return apiClient.post('/auth/forgot-password', { email })
  }

  // Reset password
  async resetPassword(token: string, password: string): Promise<ApiResponse> {
    return apiClient.post('/auth/reset-password', { token, password })
  }

  // Change password
  async changePassword(currentPassword: string, newPassword: string): Promise<ApiResponse> {
    return apiClient.post('/auth/change-password', {
      currentPassword,
      newPassword,
    })
  }

  // Update profile
  async updateProfile(data: Partial<User>): Promise<ApiResponse<{ user: User }>> {
    return apiClient.patch('/auth/profile', data)
  }

  // Verify email
  async verifyEmail(token: string): Promise<ApiResponse> {
    return apiClient.post('/auth/verify-email', { token })
  }

  // Resend verification email
  async resendVerificationEmail(): Promise<ApiResponse> {
    return apiClient.post('/auth/resend-verification')
  }

  // Check if user is authenticated
  isAuthenticated(): boolean {
    return apiClient.isAuthenticated()
  }

  // Get stored tokens
  getTokens(): { accessToken: string | null; refreshToken: string | null } {
    return {
      accessToken: localStorage.getItem('accessToken'),
      refreshToken: localStorage.getItem('refreshToken'),
    }
  }

  // Clear stored tokens
  clearTokens(): void {
    apiClient.clearTokens()
  }
}

export const authService = new AuthService()
